<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加调胎记录 - <span th:text="${tire.tireNumber}"></span></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .operation-type-card {
            cursor: pointer;
            transition: all 0.3s;
        }
        .operation-type-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .operation-type-card.selected {
            border-color: #0d6efd;
            background-color: #f8f9fa;
        }
        .hidden-section {
            display: none;
        }
        .photo-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        .photo-preview {
            position: relative;
            width: 100px;
            height: 100px;
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid #dee2e6;
        }
        .photo-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .remove-photo {
            position: absolute;
            top: 2px;
            right: 2px;
            background: rgba(0,0,0,0.7);
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            cursor: pointer;
        }
        .upload-progress {
            margin-top: 10px;
        }
        .progress {
            height: 8px;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
        <a class="navbar-brand" href="/api/tires">轮胎管理系统</a>
        <div class="navbar-nav me-auto">
            <a class="nav-link" href="/api/tires">轮胎列表</a>
        </div>
        <span class="navbar-text">
            轮胎号: <strong th:text="${tire.tireNumber}"></strong>
        </span>
    </div>
</nav>

<div class="container mt-4">
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="/api/tires">轮胎列表</a></li>
            <li class="breadcrumb-item"><a th:href="@{/api/tires/{id}(id=${tire.id})}" th:text="${tire.tireNumber}"></a></li>
            <li class="breadcrumb-item active">添加调胎记录</li>
        </ol>
    </nav>

    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h4>添加调胎记录 - <span th:text="${tire.tireNumber}"></span></h4>
                </div>
                <div class="card-body">
                    <!-- 操作类型选择 -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <label class="form-label mb-3">选择操作类型</label>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <div class="card operation-type-card" id="swapCard" onclick="selectOperation('swap')">
                                        <div class="card-body text-center">
                                            <h5 class="card-title">🔄 正常调胎</h5>
                                            <p class="card-text text-muted">将轮胎从一个位置调到另一个位置</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="card operation-type-card" id="scrapCard" onclick="selectOperation('scrap')">
                                        <div class="card-body text-center">
                                            <h5 class="card-title">🗑️ 调胎报废</h5>
                                            <p class="card-text text-muted">调胎过程中发现轮胎需要报废</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" id="operationType" name="operationType" value="swap">
                        </div>
                    </div>

                    <!-- 修改表单提交路径，添加 /api 前缀 -->
                    <form th:action="@{/api/tires/{id}/swap(id=${tire.id})}" method="post" id="swapForm" enctype="multipart/form-data">
                        <input type="hidden" name="operationType" id="operationTypeInput" value="swap">

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="swapDate" class="form-label">操作日期</label>
                                <input type="date" class="form-control" id="swapDate" name="swapDate"
                                       th:value="${currentDate}" required>
                            </div>
                            <div class="col-md-6">
                                <label for="swapMileage" class="form-label">公里数</label>
                                <input type="number" class="form-control" id="swapMileage" name="swapMileage"
                                       min="0" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="swapCost" class="form-label">费用</label>
                                <input type="number" class="form-control" id="swapCost" name="swapCost"
                                       step="0.01" min="0" value="0" required>
                            </div>
                        </div>

                        <!-- 调胎前位置 -->
                        <div class="card mb-3">
                            <div class="card-header bg-light">
                                <h6 class="mb-0">调胎前位置</h6>
                            </div>
                            <div class="card-body">
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="fromVehiclePlateNumber" class="form-label">车头牌号</label>
                                        <input type="text" class="form-control" id="fromVehiclePlateNumber"
                                               name="fromVehiclePlateNumber" th:value="${tire.vehiclePlateNumber}">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="fromTrailerPlateNumber" class="form-label">挂车牌号</label>
                                        <input type="text" class="form-control" id="fromTrailerPlateNumber"
                                               name="fromTrailerPlateNumber" th:value="${tire.trailerPlateNumber}">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="fromAxleNumber" class="form-label">轴号</label>
                                        <select class="form-select" id="fromAxleNumber" name="fromAxleNumber">
                                            <option value="">-- 选择轴号 --</option>
                                            <option th:each="axle : ${axleOptions}"
                                                    th:value="${axle}"
                                                    th:text="${axle} + '轴'"
                                                    th:selected="${tire.axleNumber != null and tire.axleNumber == axle}">
                                            </option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="fromTirePosition" class="form-label">位置</label>
                                        <select class="form-select" id="fromTirePosition" name="fromTirePosition">
                                            <option value="">-- 选择位置 --</option>
                                            <option th:each="position : ${positionOptions}"
                                                    th:value="${position}"
                                                    th:text="${position}"
                                                    th:selected="${tire.tirePosition != null and tire.tirePosition == position}">
                                            </option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 调胎后位置（正常调胎时显示） -->
                        <div class="card mb-3" id="toPositionSection">
                            <div class="card-header bg-light">
                                <h6 class="mb-0">调胎后位置</h6>
                            </div>
                            <div class="card-body">
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="toVehiclePlateNumber" class="form-label">车头牌号</label>
                                        <input type="text" class="form-control" id="toVehiclePlateNumber"
                                               name="toVehiclePlateNumber">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="toTrailerPlateNumber" class="form-label">挂车牌号</label>
                                        <input type="text" class="form-control" id="toTrailerPlateNumber"
                                               name="toTrailerPlateNumber">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="toAxleNumber" class="form-label">轴号</label>
                                        <select class="form-select" id="toAxleNumber" name="toAxleNumber">
                                            <option value="">-- 选择轴号 --</option>
                                            <option th:each="axle : ${axleOptions}"
                                                    th:value="${axle}"
                                                    th:text="${axle} + '轴'">
                                            </option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="toTirePosition" class="form-label">位置</label>
                                        <select class="form-select" id="toTirePosition" name="toTirePosition">
                                            <option value="">-- 选择位置 --</option>
                                            <option th:each="position : ${positionOptions}"
                                                    th:value="${position}"
                                                    th:text="${position}">
                                            </option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 报废确认（调胎报废时显示） -->
                        <div class="card mb-3 hidden-section" id="scrapConfirmationSection">
                            <div class="card-header bg-warning">
                                <h6 class="mb-0">⚠️ 报废确认</h6>
                            </div>
                            <div class="card-body">
                                <div class="alert alert-warning">
                                    <h6>确认要将此轮胎标记为报废吗？</h6>
                                    <p class="mb-0">此操作将：</p>
                                    <ul class="mb-2">
                                        <li>标记轮胎为报废状态</li>
                                        <li>记录报废日期和公里数</li>
                                        <li>轮胎将不再出现在可用轮胎列表中</li>
                                    </ul>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="confirmScrap" name="confirmScrap">
                                    <label class="form-check-label" for="confirmScrap">
                                        我确认要将轮胎 <strong th:text="${tire.tireNumber}"></strong> 标记为报废
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- 照片上传部分 -->
                        <div class="card mb-3">
                            <div class="card-header bg-light">
                                <h6 class="mb-0">调胎照片（可选）</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label for="swapPhotos" class="form-label">上传调胎照片</label>
                                    <input type="file" class="form-control" id="swapPhotos" name="swapPhotos"
                                           multiple accept="image/*" onchange="previewPhotos(this)">
                                    <small class="text-muted">可上传多张调胎过程的照片，支持 JPG、PNG 格式</small>

                                    <!-- 照片预览区域 -->
                                    <div class="photo-preview-container" id="photoPreview"></div>

                                    <!-- 上传进度 -->
                                    <div class="upload-progress d-none" id="uploadProgress">
                                        <div class="progress">
                                            <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                                        </div>
                                        <small class="text-muted">上传中...</small>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="swapNote" class="form-label">备注</label>
                            <textarea class="form-control" id="swapNote" name="swapNote" rows="3"
                                      placeholder="可输入调胎原因、操作人员、报废原因等信息"></textarea>
                        </div>

                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <!-- 修改取消按钮的返回路径，添加 /api 前缀 -->
                            <a th:href="@{/api/tires/{id}(id=${tire.id})}" class="btn btn-secondary me-md-2">取消</a>
                            <button type="submit" class="btn btn-primary" id="submitButton">保存调胎记录</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 操作类型选择
    function selectOperation(type) {
        const swapCard = document.getElementById('swapCard');
        const scrapCard = document.getElementById('scrapCard');
        const toPositionSection = document.getElementById('toPositionSection');
        const scrapConfirmationSection = document.getElementById('scrapConfirmationSection');
        const operationTypeInput = document.getElementById('operationTypeInput');
        const submitButton = document.getElementById('submitButton');
        const confirmScrap = document.getElementById('confirmScrap');

        // 重置所有选择
        swapCard.classList.remove('selected');
        scrapCard.classList.remove('selected');
        toPositionSection.classList.add('hidden-section');
        scrapConfirmationSection.classList.add('hidden-section');

        // 设置确认复选框为未选中
        if (confirmScrap) {
            confirmScrap.checked = false;
        }

        if (type === 'swap') {
            swapCard.classList.add('selected');
            toPositionSection.classList.remove('hidden-section');
            operationTypeInput.value = 'swap';
            submitButton.textContent = '保存调胎记录';
            submitButton.classList.remove('btn-warning');
            submitButton.classList.add('btn-primary');
        } else if (type === 'scrap') {
            scrapCard.classList.add('selected');
            scrapConfirmationSection.classList.remove('hidden-section');
            operationTypeInput.value = 'scrap';
            submitButton.textContent = '确认报废';
            submitButton.classList.remove('btn-primary');
            submitButton.classList.add('btn-warning');
        }
    }

    // 照片预览功能
    function previewPhotos(input) {
        const previewContainer = document.getElementById('photoPreview');
        previewContainer.innerHTML = '';

        if (input.files && input.files.length > 0) {
            for (let i = 0; i < input.files.length; i++) {
                const file = input.files[i];
                const reader = new FileReader();

                reader.onload = function(e) {
                    const previewDiv = document.createElement('div');
                    previewDiv.className = 'photo-preview';

                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.alt = '预览图片';

                    const removeBtn = document.createElement('button');
                    removeBtn.type = 'button';
                    removeBtn.className = 'remove-photo';
                    removeBtn.innerHTML = '×';
                    removeBtn.onclick = function() {
                        previewDiv.remove();
                        // 从文件列表中移除对应的文件
                        const dt = new DataTransfer();
                        const files = input.files;
                        for (let j = 0; j < files.length; j++) {
                            if (j !== i) {
                                dt.items.add(files[j]);
                            }
                        }
                        input.files = dt.files;
                    };

                    previewDiv.appendChild(img);
                    previewDiv.appendChild(removeBtn);
                    previewContainer.appendChild(previewDiv);
                };

                reader.readAsDataURL(file);
            }
        }
    }

    // 在表单提交前添加调试
    document.getElementById('swapForm').addEventListener('submit', function(e) {
        const operationType = document.getElementById('operationTypeInput').value;
        const toVehiclePlateNumber = document.getElementById('toVehiclePlateNumber').value.trim();
        const toTrailerPlateNumber = document.getElementById('toTrailerPlateNumber').value.trim();
        const toAxleNumber = document.getElementById('toAxleNumber').value;
        const toTirePosition = document.getElementById('toTirePosition').value;

        // 如果车头牌号为空，设置为空字符串而不是null
        document.getElementById('toVehiclePlateNumber').value = toVehiclePlateNumber;
        document.getElementById('toTrailerPlateNumber').value = toTrailerPlateNumber;

        console.log("表单提交数据:");
        console.log("操作类型:", operationType);
        console.log("调胎后位置 - 车头:", toVehiclePlateNumber, "挂车:", toTrailerPlateNumber, "轴号:", toAxleNumber, "位置:", toTirePosition);

        if (operationType === 'scrap') {
            const confirmScrap = document.getElementById('confirmScrap');
            if (!confirmScrap.checked) {
                e.preventDefault();
                alert('请确认报废操作');
                return false;
            }
        }

        // 如果有照片，使用 AJAX 提交以便显示进度
        const files = document.getElementById('swapPhotos').files;
        if (files.length > 0) {
            e.preventDefault();

            const uploadProgress = document.getElementById('uploadProgress');
            const progressBar = uploadProgress.querySelector('.progress-bar');
            uploadProgress.classList.remove('d-none');

            const formData = new FormData(this);

            // 使用XMLHttpRequest提交以便跟踪进度
            const xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    progressBar.style.width = percentComplete + '%';
                    progressBar.textContent = Math.round(percentComplete) + '%';
                }
            });

            xhr.addEventListener('load', function() {
                if (xhr.status === 200) {
                    // 上传成功，重定向到轮胎详情页面
                    window.location.href = document.querySelector('a.btn-secondary').href;
                } else {
                    alert('提交失败: ' + xhr.responseText);
                    uploadProgress.classList.add('d-none');
                }
            });

            xhr.addEventListener('error', function() {
                alert('提交过程中发生错误');
                uploadProgress.classList.add('d-none');
            });

            xhr.open('POST', this.action);
            xhr.send(formData);
        }
        // 如果没有照片，让表单正常提交
        return true;
    });

    // 页面加载时默认选择正常调胎
    document.addEventListener('DOMContentLoaded', function() {
        selectOperation('swap');

        // 设置当前公里数为轮胎的当前公里数（如果有的话）
        const currentMileage = /*[[${tire.currentMileage}]]*/ null;
        if (currentMileage) {
            document.getElementById('swapMileage').value = currentMileage;
        }
    });
</script>
</body>
</html>